package transaction

import (
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	pb "github.com/hyperledger/fabric-protos-go/peer"
)

func getArgs(envelope *common.Envelope) ([]string, error) {
	payload := &common.Payload{}
	err := proto.Unmarshal(envelope.Payload, payload)
	if err != nil {
		return nil, err
	}
	transactionAction := &pb.TransactionAction{}
	err = proto.Unmarshal(payload.Data, transactionAction)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("  |---> transactionAction:\n%#v\n", transactionAction)
	//g.Dump(transactionAction)

	chaincodeActionPayload := &pb.ChaincodeActionPayload{}
	err = proto.Unmarshal(transactionAction.Header, chaincodeActionPayload)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("  |---> chaincodeActionPayload:\n%#v\n", chaincodeActionPayload)
	//fmt.Printf("  |---> chaincodeActionPayload.Action:\n%#v\n", *chaincodeActionPayload.Action)
	//g.Dump(*chaincodeActionPayload)
	chaincodeProposalPayload := &pb.ChaincodeProposalPayload{}
	err = proto.Unmarshal(chaincodeActionPayload.Action.ProposalResponsePayload, chaincodeProposalPayload)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("  |---> chaincodeProposalPayload:\n%#v\n", chaincodeProposalPayload)

	// --------------------------- 链码参数 -------------------
	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{}
	err = proto.Unmarshal(chaincodeProposalPayload.Input, chaincodeInvocationSpec)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("  |---> chaincodeInvocationSpec:\n%#v\n", *chaincodeInvocationSpec)
	//fmt.Printf("  |---> chaincodeInvocationSpec.ChaincodeSpec:\n%#v\n", *chaincodeInvocationSpec.ChaincodeSpec)
	//fmt.Printf("  |---> chaincodeInvocationSpec:\n%#v\n", *chaincodeInvocationSpec.ChaincodeSpec.ChaincodeId)
	//fmt.Printf("  |---> chaincodeInvocationSpec:\n%#v\n", *chaincodeInvocationSpec.ChaincodeSpec.Input)

	sArgs := make([]string, 0)
	args := chaincodeInvocationSpec.ChaincodeSpec.Input.GetArgs()
	for _, v := range args {
		//fmt.Printf("  |---> [%v] = %v\n", k, string(v))
		sArgs = append(sArgs, string(v))
	}
	//fmt.Printf("  |---> chaincodeInvocationSpec.Id.:\n%#v\n", *chaincodeInvocationSpec)

	// --------------------------- 链码参数 -------------------
	//fmt.Printf("  |---> chaincodeProposalPayload.TransientMap:\n%#v\n", chaincodeProposalPayload.TransientMap)

	return sArgs, nil
}
